//
//  BSMettController.m
//  BusinessSchool
//
//  Created by 化 on 14-6-20.
//  Copyright (c) 2014年 化. All rights reserved.
//

#import "BSMettController.h"
#import "MSScrollView.h"
#import "MeetingDetailViewController.h"
#import "BSAppDelegate.h"
#import "RequestServer.h"
#import "SBJsonWriter.h"
#import "JSON.h"

@interface BSMettController ()<TapImageDelegate,RequestServerDelegate>

@end

@implementation BSMettController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"学堂会议";
    self.view.backgroundColor = [UIColor colorWithHexString:@"f0f0f0"];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(10, 0, 30, 30);
    [button setImage:[UIImage imageNamed:@"返回.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    db = [[SQLite alloc] initWithDbName:[defaults objectForKey:@"CurrentDataBaseName"]];
    
    current_Page = 1;
    self->refreshHeaderView.hidden = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    listdata = [[NSMutableArray alloc]init];
    eventReader = [[NSMutableArray alloc]init];
    if (refreshHeaderView == nil) {
           EGORefreshTableHeaderView * view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0, 0-self.tableView.frame.size.height, self.tableView.frame.size.width, self.tableView.frame.size.height)];
        view.delegate = self;
        [self.tableView addSubview:view];
        refreshHeaderView = view;
        [view release];
    }


    [refreshHeaderView refreshLastUpdatedDate];
    
    [self request];
}

-(void)viewDidAppear:(BOOL)animated
{
    [self.tableView reloadData];
}

#pragma mark 返回
-(void)goBack
{
    [self.navigationController popViewControllerAnimated:YES];
}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 1) {
        return 1;
    }
    return [listdata count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        return 40;
    }
    return 65;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        static NSString *CellIdentifier = @"cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        cell = nil;
        if (nil == cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
        
        UIButton *loadButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [loadButton setFrame:CGRectMake(0, 0, 320, 40)];
        if ([listdata count] < current_Page*10) {
            [loadButton setTitle:@"已是最后一页" forState:UIControlStateNormal];
        }else{
            [loadButton setTitle:@"加载更多..." forState:UIControlStateNormal];
        }
        [loadButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        loadButton.backgroundColor = [UIColor clearColor];
        [loadButton addTarget:self action:@selector(loadMore:) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:loadButton];
        return cell;
    } else {
        
        NSString* reuseIdentifier = [NSString stringWithFormat:@"section=%d,row=%d", indexPath.section, indexPath.row];
        UITableViewCell* cell = nil;
        if (nil == cell) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier] autorelease];
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        NSString *titleMutablString = [NSString stringWithFormat:@"%@",[[listdata objectAtIndex:indexPath.row]objectForKey:@"title"]];
        
        if ([titleMutablString isEqualToString:@"(null)"] || titleMutablString.length == 0) {
            [cell.textLabel setText:@"暂无"];
        }else{
            NSString *titleStr = nil;
            if (titleMutablString.length > 12) {
                titleStr = [NSString stringWithFormat:@"%@...", [titleMutablString substringWithRange:NSMakeRange(0, 12)]];
            }else {
                titleStr = [NSString stringWithFormat:@"%@", [titleMutablString substringWithRange:NSMakeRange(0, [titleMutablString length])]];
            }
            [cell.textLabel setText:titleStr];
        }
        
        if ([eventReader containsObject:[NSString stringWithFormat:@"%d",indexPath.row]]  || [[[listdata objectAtIndex:indexPath.row]objectForKey:@"IsRead"]isEqualToString:@"yes"]) {
            cell.textLabel.textColor =[UIColor grayColor];
        }
        [cell.textLabel setFont:[UIFont fontWithName:@"Helvetica" size:15.0]];
        cell.selectionStyle =UITableViewCellSelectionStyleBlue;
        cell.detailTextLabel.numberOfLines = 0;
        cell.detailTextLabel.lineBreakMode = NSLineBreakByCharWrapping;//自动换行
        [cell.detailTextLabel setFont:[UIFont boldSystemFontOfSize:10]];
        //将附标题和时间整合到一起在第二行显示
        NSString *subTitleAndTime;
        if ([[listdata objectAtIndex:indexPath.row]objectForKey:@"createDate"]== NULL || [[[listdata objectAtIndex:indexPath.row]objectForKey:@"createDate"] isEqualToString:@"(null)"]) {
            subTitleAndTime =[NSString stringWithFormat:@"暂无"];
        }else
        {
            subTitleAndTime =[NSString stringWithFormat:@"%@",[[listdata objectAtIndex:indexPath.row]objectForKey:@"createDate"]];
        }
        //        NSString *detailStr = nil;
        UILabel *detailTitle = [[UILabel alloc]initWithFrame:CGRectMake(10, cell.height - 17, 230, 40)];
        detailTitle.text = subTitleAndTime;
        detailTitle.numberOfLines = 2;
        detailTitle.backgroundColor = [UIColor clearColor];
        detailTitle.font = [UIFont fontWithName:@"Helvetica" size:12.0];
        detailTitle.textColor = [UIColor grayColor];
        [cell addSubview:detailTitle];
        [detailTitle release];
        
        cell.detailTextLabel.textColor = [UIColor grayColor];
        cell.selectionStyle =UITableViewCellSelectionStyleBlue;
        cell.detailTextLabel.textAlignment = NSTextAlignmentLeft;
        [cell.textLabel setFont:[UIFont boldSystemFontOfSize:18]];
        [cell.detailTextLabel setFont:[UIFont systemFontOfSize:12]];
        cell.detailTextLabel.textColor = [UIColor clearColor];
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@",subTitleAndTime];
        cell.detailTextLabel.numberOfLines = 2;
        
        UIImageView *bgImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@""]];
        bgImage.frame = CGRectMake(0, 0, self.view.width, 65);
        UIImageView *bgImageLine = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"line.png"]];
        bgImageLine.frame = CGRectMake(0, 63, self.view.width, 2);
        [bgImage addSubview:bgImageLine];
        cell.backgroundView = bgImage;
        
        cell.selectionStyle =  UITableViewCellSelectionStyleNone;
        [bgImage release];
        [bgImageLine release];
        
        
        return cell;
    }
}

#pragma mark 每行新闻点击时间
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    MeetingDetailViewController* viewController = [[MeetingDetailViewController alloc] initWithStyle:UITableViewStylePlain withContentId:[listdata objectAtIndex:indexPath.row]];
    viewController.tag = 2;
    [self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark banner点击事件
- (void)tapImage:(int)index
{
    
}

#pragma mark 加载更多事件
- (void)loadMore:(id)sender
{
    current_Page += 1;
    
    NSString *selesql = [NSString stringWithFormat:@"select * from huiyi  ORDER BY createDate  DESC limit '%d'",current_Page*10];
    if ([listdata count] == [[db querryTable:selesql] count]) {
        ShowMessage(@"已是最后一页");
        return;
    }
    [listdata removeAllObjects];
    listdata = [NSMutableArray arrayWithArray:[db querryTable:selesql]];
    [listdata retain];
    [self.tableView reloadData];
}

#pragma mark 下拉刷新时间
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (!self->refreshHeaderView.hidden) {
        [self->refreshHeaderView egoRefreshScrollViewDidEndDragging:self.tableView];
    }
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{

    current_Page = 1;
    [self request];
    
    return [NSDate date];
}
//已改
#pragma mark 请求数据
- (void)request
{
    
    
    NSMutableDictionary *defaults = [[NSMutableDictionary alloc] init];
    NSString *getTheLasttime =@"select * from huiyi  ORDER BY upDatetime  DESC";
    NSArray *array_time = [db querryTableByCallBack:getTheLasttime];
    if ([array_time count] > 0) {
        NSString *NewsLastreleaseTime =[[array_time objectAtIndex:0]objectForKey:@"upDatetime"];
        [defaults setObject:NewsLastreleaseTime forKey:@"upDate"];
    }else{
        [defaults setObject:@"" forKey:@"upDate"];
    }
    
    [defaults setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"userId"] forKey:@"userId"];
    
    [[RequestServer instance] doActionAsync:0 withAction:@"com.haoqee.businessSchool.client.action.MeetingAction$getNewMeeting" withParameters:defaults withDelegate:self];
}


- (void)requestFinished:(NSNumber *)code withMessage:(NSString *)message withData:(id)data
{
    if (code == 0) {
        
        
        NSMutableArray *dataArray = [NSMutableArray arrayWithArray:data];
        NSMutableArray *insertsql = [[NSMutableArray alloc]init];
        
        for (int i = 0 ; i<[dataArray count]; i++) {
            
            NSString *idString = [NSString stringWithFormat:@"%@",[[dataArray objectAtIndex:i] objectForKey:@"id"]];
            NSString *createDateString = [NSString stringWithFormat:@"%@",[[dataArray objectAtIndex:i]objectForKey:@"createDate"]];
            NSString *titleString = [NSString stringWithFormat:@"%@",[[dataArray objectAtIndex:i]objectForKey:@"title"]];
            NSString *createUserString = [NSString stringWithFormat:@"%@",[[dataArray objectAtIndex:i] objectForKey:@"createUser"]];
            NSString *upDateString = [NSString stringWithFormat:@"%@",[[dataArray objectAtIndex:i] objectForKey:@"upDate"]];
            
            
            NSString *selectsql = [NSString stringWithFormat:@"select * from huiyi where id = '%@'",idString];
            NSArray *sarray = [db querryTableByCallBack:selectsql];
            if ([sarray count] <= 0) {
                NSString *execute = [NSString stringWithFormat:@"INSERT INTO huiyi  (id,title,context,closeTime,createUser,createDate,upDatetime,files)values('%@','%@','%@','%@','%@','%@','%@','%@')",idString,titleString,@"",@"",createUserString,createDateString,upDateString,@""];
                [insertsql addObject:execute];
                
            }
        }
        
        
        if (![db updateGreatTable:insertsql]) {
            NSLog(@"插入表失败");
        }
        
        NSString *selesql = [NSString stringWithFormat:@"select * from huiyi  ORDER BY createDate  DESC limit 10"];
        listdata = [NSMutableArray arrayWithArray:[db querryTable:selesql]];
        [listdata retain];
        [self.tableView reloadData];
        
    }else{
        NSLog(@"请求失败");
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
